package com.bsj.pay.util.platform.wsgw;

import com.bsj.pay.common.ChargeOrder;
import com.bsj.pay.config.GlobalConfig;
import com.bsj.pay.dao.AccountDao;
import com.bsj.pay.model.AccountBean;
import com.bsj.pay.model.ChargeAccountBean;
import com.bsj.pay.model.GoodsBean;
import com.bsj.pay.model.OrderBean;
import com.bsj.pay.model.StoreBean;
import com.bsj.pay.model.weidian.ConfirmOrderResultVo;
import com.bsj.pay.model.weidian.LoginQueryVo;
import com.bsj.pay.model.weidian.PayInfoVo;
import com.bsj.pay.model.weidian.PayResultQueryVo;
import com.bsj.pay.service.AccountService;
import com.bsj.pay.service.GoodsService;
import com.bsj.pay.service.OrderService;
import com.bsj.pay.service.PayPoolService;
import com.bsj.pay.service.StoreService;
import com.bsj.pay.util.http.Http;
import com.bsj.pay.util.http.Http.RequestType;
import com.bsj.pay.util.http.Http.Response;
import com.bsj.pay.util.platform.PayInterface;
import com.bsj.pay.util.platform.PlatformInterface;
import net.sf.json.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component("weidianUtil")
public class WeiDianUtil implements PlatformInterface, PayInterface {
    private static final Logger log = LogManager.getLogger(WeiDianUtil.class);

    private static String queryOrderType = "order";

    @Autowired
    private AccountService accountService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private StoreService storeService;

    @Autowired
    private OrderService orderService;

    @Resource
    private AccountDao accountDao;

    @Autowired
    private PayPoolService payPoolService;

    public Map<String, String> createOrder(ChargeAccountBean chargeAccount, GoodsBean goods, AccountBean account, OrderBean order) throws Exception {
        Map<String, String> orderMap = null;
        for (int i = 0; i < 3; i++) {
            try {
                Map<String, String> resultMap = payPoolService.getOneCanUsePayUrl(goods.getAmount(), order.getPay_type());
                if (resultMap != null) {
                    return resultMap;
                }
                return getPayUrl(goods, order.getPay_type(), account);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                if (e.getMessage() != null && i < 2) {
                    if (e.getMessage().contains("网络链接失败")) {
                        log.info("账号:{},下单网络链接失败,重新绑定代理ip", account.getAccount());
                        accountService.updateAccountProxy(account);
                    } else if (e.getMessage().contains("下单失败")) {
                        Thread.sleep(1000);
                    } else if (e.getMessage().contains("LOGIN ERROR")) {
                        AccountBean updateAccount = new AccountBean();
                        updateAccount.setId(account.getId());
                        updateAccount.setLogin_status(2);
                        accountDao.update(updateAccount);
                        AccountBean accountNew = accountDao.getOneCanDispatchOrderByAuthType("weidian", GlobalConfig.order_account_type);
                        if (accountNew == null) {
                            throw new Exception("暂无购买账号，请稍后再试!");
                        }
                        OrderBean updateOrder = new OrderBean();
                        updateOrder.setId(order.getId());
                        order.setAccount_id(account.getId());
                        order.setAccount(account.getAccount());
                        orderService.update(updateOrder);
                        account = accountNew;
                    }
                } else {
                    GoodsBean updateGoods = new GoodsBean();
                    updateGoods.setId(goods.getId());
                    updateGoods.setStatus(0); // 设置商品失效
                    goodsService.update(updateGoods);
                    throw e;
                }
            }
        }

        return null;
    }

    @Override
    public Map<String, String> getPayUrl(GoodsBean goods, String payType, AccountBean account) throws Exception {
        Map<String, String> resultMap = new HashMap<String, String>();
        Map<String, String> headers = new HashMap<String, String>();
        String url = "http://120.78.146.96:6677/get_pay_url";
        // if (payType.startsWith("wechat")) {
        //     url = "http://120.78.146.96:6677/get_pay_url";
        // }
        headers.put("User-Agent", "wang shang guo wang/2.2.3 (iPhone; iOS 14.1; Scale/3.00)");
        headers.put("version", "2.2.3");
        // headers.put("Cookie", account.getLogin_cookie());

        PayInfoVo payInfoVo = new PayInfoVo();
        payInfoVo.setCookies(account.getLogin_cookie());
        payInfoVo.setProxy(account.getProxy_ip() + ":" + account.getProxy_port());
        // TODO: 2022/12/11 修改商品信息
        // payInfoVo.setItemID(chargeAccountBean.getId().toString());
        // payInfoVo.setAmount(chargeAccountBean.getAmount());
        // payInfoVo.setItemID("5944683662");
        String googsLink = goods.getGoods_link();
        payInfoVo.setItemID(googsLink.substring(googsLink.indexOf("=") + 1, googsLink.length()).trim());
        payInfoVo.setAmount(1);
        payInfoVo.setPay_type(payType);

        Response res = Http.create(url).heads(headers).requestType(RequestType.JSON).bodys(payInfoVo).post().send().getResponse();
        String result = res.getResult();
        if (res.getStatus() == 0 || StringUtils.isEmpty(result)) {
            throw new Exception("网络链接失败，请重试!");
        }
        log.info("[微店]获取支付链接---结果:{},耗时:{},状态:{}", result, res.getTime(), res.getStatus());
        JSONObject jsonObject = JSONObject.fromObject(result);
        String status = jsonObject.optString("status", "");
        JSONObject data = jsonObject.optJSONObject("data");
        if (!StringUtils.isEmpty(status) && !status.equals("success")) {
            // TODO: 2022/12/16 下单失败后，更改该商品为为失效
            JSONObject status1 = data.getJSONObject("status");
            if (status1 != null) {
                int code = status1.optInt("code", 0);
                if (code == 2) {
                    throw new Exception("LOGIN ERROR");
                }
            }
            throw new Exception("下单失败");
        }
        if (data == null) {
            throw new Exception("下单失败");
        }

        JSONObject order_data = data.optJSONObject("order_data");
        String order_id = order_data.optString("orderId", "");
        String payUrlKey = "par_url";
        String notifyTokenKey = "";
        if (payType.equalsIgnoreCase("alipay")) {
            payUrlKey = "payUrl";
            notifyTokenKey = "notifyToken";
        }

        if (StringUtils.hasLength(notifyTokenKey)) {
            String notifyToken = order_data.getString(notifyTokenKey);
            resultMap.put("notifyToken", notifyToken);
        }
        String payUrl = order_data.getString(payUrlKey);
        String cookies = data.getString("cookies");

        resultMap.put("payUrl", payUrl);
        resultMap.put("goodsId", goods.getId().toString());
        resultMap.put("cookies", cookies);

        // TODO: 2022/12/9 保存下单cookies，用于后续查询订单
        log.info("[微店]获取支付链接---订单号:{},交易号:,结果:{},耗时:{},状态:{}", order_id, resultMap.get("payUrl"), res.getTime(), res.getStatus());
        resultMap.put("orderNo", order_id);
        return resultMap;
    }

    public Map<String, String> online(AccountBean account) throws Exception {
        AccountBean updateModel = new AccountBean();
        updateModel.setId(account.getId());
        if (!StringUtils.isEmpty(account.getLogin_cookie())) {
            // 数据库中判断10小时后cookie进行重新获取并更新login_cookie
            try {
                Map<String, String> resultMap = this.login(account);
                if (resultMap.get("status").equalsIgnoreCase("success")) {
                    updateModel.setLogin_cookie_expire_time(System.currentTimeMillis() / 1000);
                    updateModel.setLogin_status(1);
                    updateModel.setRemarks("");
                    accountService.update(updateModel);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                if (e.getMessage() != null) {
                    if (e.getMessage().contains("网络链接失败")) {
                        log.info("账号:{},检测账号网络链接失败,重新绑定代理ip", account.getAccount());
                        accountService.updateAccountProxy(account);
                    }
                } else {
                    throw e;
                }
            }
        }
        // else if (!StringUtils.isEmpty(account.getPassword())) {
        //     Map<String, String> resultMap = this.login(account);
        //     updateModel.setLogin_cookie(resultMap.get("token"));
        //     updateModel.setInfo(resultMap.get("userId"));
        //     updateModel.setUpdate_time(System.currentTimeMillis() / 1000);
        //     accountService.update(updateModel);
        // }
        return null;
    }

    public Map<String, String> login(AccountBean account) throws Exception {
        Map<String, String> headers = new HashMap<String, String>();

        String url = "http://120.78.146.96:6677/get_user_info";
        headers.put("User-Agent", "wang shang guo wang/2.2.3 (iPhone; iOS 14.1; Scale/3.00)");
        headers.put("version", "2.2.3");

        LoginQueryVo queryVo = new LoginQueryVo();
        queryVo.setCookies(account.getLogin_cookie());
        queryVo.setProxy(account.getProxy_ip() + ":" + account.getProxy_port());

        Response res = Http.create(url).heads(headers).requestType(RequestType.JSON).bodys(queryVo).post().send().getResponse();
        String result = res.getResult();
        if (res.getStatus() == 0 || StringUtils.isEmpty(result)) {
            throw new Exception("网络链接失败，请重试!");
        }
        log.info("[微店]获取用户信息---结果:{},耗时:{},状态:{}", result, res.getTime(), res.getStatus());
        JSONObject jsonObject = JSONObject.fromObject(result);

        String status = jsonObject.optString("status", "");
        if (!StringUtils.isEmpty(status) && !status.equals("success")) {
            throw new Exception("其他错误");
        }
        Map<String, String> resultMap = new HashMap<String, String>();
        resultMap.put("status", status);
        return resultMap;
    }

    public List<ChargeOrder> queryTransList(AccountBean account, boolean status) throws Exception {
        List<ChargeOrder> onlineOrderList = new ArrayList<ChargeOrder>();
        return onlineOrderList;
    }

    public List<ChargeOrder> queryTransList(AccountBean account, int page, int limit) throws Exception {
        List<ChargeOrder> onlineOrderList = new ArrayList<ChargeOrder>();
        return onlineOrderList;
    }

    public Map<String, String> orderDetail(OrderBean order, AccountBean account, int notify_type) throws Exception {
        Map<String, String> resultMap = new HashMap<String, String>();

        String orderNo = order.getOfficial_order_no();
        Map<String, String> headers = new HashMap<String, String>();
        //String url="https://payctl.95598pay.com/payunifycontroller/rest/payunify/zfbpay";
    	/*if(order.getPay_type().startsWith("wechat"))
    	{
    		url="https://payctl.95598pay.com/payunifycontroller/rest/payunify/wxpay";
    	}*/
        String url = "http://120.78.146.96:6677/get_pay_result";
        headers.put("User-Agent", "wang shang guo wang/2.2.3 (iPhone; iOS 14.1; Scale/3.00)");
        headers.put("version", "2.2.3");

        PayResultQueryVo queryVo = new PayResultQueryVo();
        queryVo.setCookies(order.getLogin_cookie());
        queryVo.setOrder_id(orderNo);
        queryVo.setProxy(account.getProxy_ip() + ":" + account.getProxy_port());

        Response res = Http.create(url).heads(headers).requestType(RequestType.JSON).bodys(queryVo).post().send().getResponse();
        String result = res.getResult();
        if (res.getStatus() == 0 || StringUtils.isEmpty(result)) {
            throw new Exception("网络链接失败，请重试!");
        }
        log.info("[微店]获取支付状态---订单号:{},结果:{},耗时:{},状态:{}", order.getOfficial_order_no(), result, res.getTime(), res.getStatus());
        JSONObject jsonObject = JSONObject.fromObject(result);

        String status = jsonObject.optString("status", "");
        if (!StringUtils.isEmpty(status) && !status.equals("success")) {
            throw new Exception("其他错误");
        }
        JSONObject data = jsonObject.getJSONObject("data");

        String pay_result = data.optString("pay_result", "");
        resultMap.put("status", "fail");
        if ("已发货".equals(pay_result)) {
            Boolean resul = confirmOrder(order, account);
            if (resul) {
                GoodsBean goods = goodsService.getById(order.getGoods_id());
                StoreBean store = storeService.getById(goods.getStore_id());
                StoreBean updateBean = new StoreBean();
                if (store.getCharge_quota() + order.getAmount() > store.getQuota()) {
                    updateBean.setStatus(0);
                }
                updateBean.setId(store.getId());
                updateBean.setCharge_quota(store.getCharge_quota() + order.getAmount());
                storeService.update(updateBean);
                resultMap.put("status", "success");
                resultMap.put("orderNo", order.getOfficial_order_no());
                return resultMap;
            }
        }
        return resultMap;
    }

    private Boolean confirmOrder(OrderBean order, AccountBean account) throws Exception {
        String orderNo = order.getOfficial_order_no();
        Map<String, String> headers = new HashMap<String, String>();
        //String url="https://payctl.95598pay.com/payunifycontroller/rest/payunify/zfbpay";
    	/*if(order.getPay_type().startsWith("wechat"))
    	{
    		url="https://payctl.95598pay.com/payunifycontroller/rest/payunify/wxpay";
    	}*/
        String url = "http://120.78.146.96:6677/confrim_order";
        headers.put("User-Agent", "wang shang guo wang/2.2.3 (iPhone; iOS 14.1; Scale/3.00)");
        headers.put("version", "2.2.3");

        ConfirmOrderResultVo queryVo = new ConfirmOrderResultVo();
        queryVo.setCookies(order.getLogin_cookie());
        queryVo.setOrder_id(orderNo);
        queryVo.setProxy(account.getProxy_ip() + ":" + account.getProxy_port());

        Response res = Http.create(url).heads(headers).requestType(RequestType.JSON).bodys(queryVo).post().send().getResponse();
        String result = res.getResult();
        if (res.getStatus() == 0 || StringUtils.isEmpty(result)) {
            throw new Exception("网络链接失败，请重试!");
        }
        log.info("[微店]确认订单状态---订单号:{},结果:{},耗时:{},状态:{}", order.getOfficial_order_no(), result, res.getTime(), res.getStatus());
        JSONObject jsonObject = JSONObject.fromObject(result);

        String status = jsonObject.optString("status", "");
        if (!StringUtils.isEmpty(status) && !status.equals("success")) {
            throw new Exception("其他错误");
        }
        return true;
    }

    @Override
    public String getQueryOrderType() {
        // TODO Auto-generated method stub
        return this.queryOrderType;
    }

    @Override
    public void setQueryOrderType(String queryOrderType) {
        this.queryOrderType = queryOrderType;
    }

    @Override
    public Map<String, String> checkChargeAccount(ChargeAccountBean chargeAccount, AccountBean account) {
        // TODO Auto-generated method stub
        return null;
    }

    public static void main(String[] args) throws Exception {
        WeiDianUtil wsgw = new WeiDianUtil();
        AccountBean account = new AccountBean();
        account.setAccount("17065491417");
        account.setPassword("iwl39817");
        wsgw.login(account);//ssha47a8adc774249a58eaa693e9727a1eb
        //account.setLogin_cookie("98taf77e6a4f435d4d44bece33bd234e69b91");
        //wsgw.queryTransList(account, 1, 10);
        //Map<String, String> orderMap =new HashMap<>();
        //orderMap.put("ORDER_ID", "320210901130320267819");
        //wsgw.getPayUrl(orderMap, "alipay", account);
        //wsgw.queryTransList(account, 1, 10);
        ChargeAccountBean chargeAccount = new ChargeAccountBean();
        chargeAccount.setAccount("6502291612");
        //chargeAccount.setOfficial_user_id("osg-p:9f1006cf-b93a-40ab-90e5-c47b65b293e6");
        chargeAccount.setArea_code("33101");
        OrderBean order = new OrderBean();
        order.setPay_type("alipay");
        order.setAmount(5);
        //wsgw.queryAccount(account);
        //System.out.println(JSONUtil.toJson(wsgw.queryCertAuth(account)));
        //wsgw.createOrder(chargeAccount, account, order);


        //order.setOfficial_order_no("9889798240716316542d8cd7_420211020120562858077");
        //System.out.println(JSONUtil.toJson(wsgw.addAccount(chargeAccount, account)));
        //System.out.println(JSONUtil.toJson(wsgw.orderDetail(order, account, 2)));
    }
}
